<template>
  <div class="major-school">
    <TitleHeader name="开设院校" />
    <div class="filter-box">
      <div class="filter-item-position">
        <span class="title">院校位置</span>
        <div
          :class="{
            positionLevel: true,
            active: showPositionTooltip,
            valued: positionDisplayName != '全部',
          }"
          @click="togglePositionTooltip"
        >
          <span>{{ positionDisplayName }}</span>
          <el-icon>
            <ArrowDown color="#BBBBBB" />
          </el-icon>
        </div>
        <positionTooltip
          :visible="showPositionTooltip"
          @confirmPosition="confirmPosition"
          @close="showPositionTooltip = false"
        />
      </div>
      <div class="filter-item-level">
        <span class="title">院校层次</span>
        <div
          :class="{
            campusLevel: true,
            active: showTooltip,
            valued: campusLevelName != '全部',
          }"
          @click="toggleTooltip"
        >
          <span>{{ campusLevelName }}</span>
          <el-icon>
            <ArrowDown color="#BBBBBB" />
          </el-icon>
          <!-- <img class="arrow" :src="dropDownArrow" alt="" /> -->
        </div>
        <campusLevelTooltip
          :visible="showTooltip"
          @confirmSchoolFeature="confirmSchoolFeature"
          @close="showTooltip = false"
        />
      </div>
      <div class="filter-item">
        <span class="title">查询院校</span>
        <el-input
          v-model="schoolName"
          @change="schoolNameChange"
          placeholder="请输入院校关键词"
          class="custom-input"
        />
      </div>
    </div>
    <div
      v-if="schoolList.length > 0"
      class="school-list"
      @scroll="debouncedListHandleScroll"
    >
      <schoolCard
        v-for="(item, index) in schoolList"
        :key="index"
        :schoolInfo="item"
      />
    </div>
    <div v-else>
      <Empty />
    </div>
  </div>
</template>

<script setup>
import dropDownArrow from '@/assets/images/dropDownArrow.png';
import closeBtn from '@/assets/images/closeBtn.png';
import { customRegionData } from '@/utils/regionData.js';
import { getNewSchoolList } from '@/api/majorSearch';
import { ref, watch, onMounted, onUnmounted } from 'vue';
import TitleHeader from './TitleHeader.vue';
import campusLevelTooltip from './campusLevelTooltip.vue';
import positionTooltip from './positionTooltip.vue';
import Empty from '@/components/empty.vue';
import schoolCard from './schoolCard.vue';
// 引入防抖函数
import antiShake from '@/utils/antiShake.js';

const props = defineProps({
  positionTagId: {
    type: String,
    default: '',
  },
});

const showTooltip = ref(false);
const showPositionTooltip = ref(false);

const toggleTooltip = () => {
  showTooltip.value = !showTooltip.value;
  // 关闭另一个 tooltip
  if (showTooltip.value) {
    showPositionTooltip.value = false;
  }
};

const togglePositionTooltip = () => {
  showPositionTooltip.value = !showPositionTooltip.value;
  // 关闭另一个 tooltip
  if (showPositionTooltip.value) {
    showTooltip.value = false;
  }
};

// 点击外部关闭 tooltip
const closeTooltipOnOutsideClick = (event) => {
  const tooltip = document.querySelector('.campus-level-tooltip');
  const positionTooltip = document.querySelector('.position-tooltip');
  const campusLevel = document.querySelector('.campusLevel');
  const positionLevel = document.querySelector('.positionLevel');

  if (
    tooltip &&
    campusLevel &&
    !tooltip.contains(event.target) &&
    !campusLevel.contains(event.target)
  ) {
    showTooltip.value = false;
  }

  if (
    positionTooltip &&
    positionLevel &&
    !positionTooltip.contains(event.target) &&
    !positionLevel.contains(event.target)
  ) {
    showPositionTooltip.value = false;
  }
};

const schoolPosition = ref([]); // 院校位置
const positionDisplayName = ref('全部'); // 显示的位置名称
const regionId = ref('');

// 处理位置选择确认
const confirmPosition = (positionData) => {
  pageNo.value = 1;
  pageSums.value = 100;

  schoolPosition.value = positionData.value;

  // 更新显示名称
  if (positionData.province && positionData.province.name) {
    positionDisplayName.value = positionData.province.name;
    regionId.value = positionData.province.value;
  } else {
    positionDisplayName.value = '全部';
    regionId.value = '';
  }

  getSchoolListFn();
};

const handlePositionChange = (value) => {
  // 保留原来的逻辑作为备用
  pageNo.value = 1;
  pageSums.value = 100;
  if (schoolPosition.value.length == 2) {
    regionId.value = schoolPosition.value[1];
  } else {
    regionId.value = schoolPosition.value[0];
  }
  getSchoolListFn();
};

const schoolName = ref(); // 院校名称
const schoolNameChange = () => {
  pageNo.value = 1;
  pageSums.value = 100;
  getSchoolListFn();
};
// 处理院校层次显示的名称
const concatFeatureNames = (obj) => {
  const keys = [
    'schoolFeatureList',
    'schoolNatureList',
    'schoolLevelList',
    'schoolTypeList',
  ];

  const allNames = [];

  keys.forEach((key) => {
    if (Array.isArray(obj[key]) && obj[key].length > 0) {
      obj[key].forEach((item) => {
        // 跳过 name 为 "不限" 或空值的项
        if (
          item.name &&
          item.name.trim() !== '' &&
          item.name.trim() !== '不限'
        ) {
          allNames.push(item.name.trim()); // 添加 trim() 去除多余空格
        }
      });
    }
  });
  return [...new Set(allNames)].join(',');
};

const campusLevelName = ref('全部');
const collegeType = ref(''); // 院校类型
const dualClassName = ref('');
const levelName = ref('');
const natureName = ref('');
// 院校层次相关逻辑
const confirmSchoolFeature = (newSchoolFeaturedObj) => {
  pageNo.value = 1;
  pageSums.value = 100;
  campusLevelName.value = concatFeatureNames(newSchoolFeaturedObj);
  if (campusLevelName.value == '') {
    campusLevelName.value = '全部';
  }
  const {
    schoolFeatureList,
    schoolNatureList,
    schoolLevelList,
    schoolTypeList,
  } = newSchoolFeaturedObj;
  collegeType.value = schoolTypeList.map((item) => item.code).join(',');
  dualClassName.value = schoolFeatureList.map((item) => item.code).join(',');
  levelName.value = schoolLevelList.map((item) => item.code).join(',');
  natureName.value = schoolNatureList.map((item) => item.code).join(',');
  getSchoolListFn();
};
const schoolList = ref([]);
const pageNo = ref(1);
const pageSums = ref(100);
const getSchoolListFn = async () => {
  const params = {
    collegeType: collegeType.value,
    dualClassName: dualClassName.value,
    levelName: levelName.value,
    natureName: natureName.value,
    pageNo: pageNo.value,
    pageSize: 10,
    matchName: schoolName.value,
    positionTagId: props.positionTagId,
    regionId: regionId.value,
  };
  const res = await getNewSchoolList(params);
  if (res.code == 200) {
    pageSums.value = res.pageparam.pages;
    if (pageNo.value == 1) {
      schoolList.value = res.data;
    } else {
      schoolList.value = [...schoolList.value, ...res.data];
    }
    pageNo.value++;
  }
};
const handleScroll = () => {
  const listElement = document.querySelector('.school-list');
  if (listElement) {
    const { scrollTop, scrollHeight, clientHeight } = listElement;
    if (scrollTop + clientHeight >= scrollHeight - 10) {
      if (pageNo.value <= pageSums.value) {
        getSchoolListFn();
      }
    }
  }
};
const debouncedListHandleScroll = antiShake(handleScroll, 300);

watch(
  () => props.positionTagId,
  (nawVal) => {
    getSchoolListFn();
  },
  { deep: true }
);

onMounted(() => {
  getSchoolListFn();
  document.addEventListener('click', closeTooltipOnOutsideClick);
});

onUnmounted(() => {
  document.removeEventListener('click', closeTooltipOnOutsideClick);
});
</script>

<style lang="scss" scoped>
.major-school {
  width: 100%;
  height: 100%;
  padding: 40px;
  box-sizing: border-box;
  .filter-box {
    display: flex;
    align-items: center;
    gap: 64px;
    .filter-item-position {
      display: flex;
      align-items: center;
      position: relative;
      .title {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24px;
        color: #555555;
        margin-right: 16px;
      }
      .positionLevel {
        width: 306px;
        height: 51px;
        background: #fafcfe;
        border-radius: 6px;
        border: 2px solid #e4edf8;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 17px 0px 20px;
        box-sizing: border-box;
        font-size: 24px;
        cursor: pointer;
        transition: all 0.3s ease;
        &.active {
          border: 2px solid #0b6eff;
          background: #e7f4ff;
          color: #0b6eff;
        }
        &.valued {
          color: #0b6eff;
        }
        span {
          display: inline-block;
          max-width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      :deep(.el-cascader) {
        width: 306px;
        height: 51px;
        background: #fafcfe;
        border-radius: 6px;
        border: 2px solid #e4edf8;
      }

      :deep(.el-cascader-menu) {
        .el-cascader-node {
          height: 500px !important;
          line-height: 500px !important;
        }
      }
      :deep(.el-input) {
        height: 100% !important;
      }
      :deep(.el-input__icon) {
        font-size: 26px;
      }
      :deep(.el-input__wrapper) {
        background: #fafcfe;
        box-shadow: none;
        // height: 100%;
      }
      :deep(.el-input__inner) {
        height: 100%;
        background: #fafcfe;
        font-size: 24px;
      }
    }
    .filter-item-level {
      display: flex;
      align-items: center;
      position: relative;
      .title {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24px;
        color: #555555;
        margin-right: 16px;
      }
      .campusLevel {
        width: 306px;
        height: 51px;
        background: #fafcfe;
        border-radius: 6px;
        border: 2px solid #e4edf8;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 17px 0px 20px;
        box-sizing: border-box;
        font-size: 24px;
        cursor: pointer;
        transition: all 0.3s ease;
        &.active {
          border: 2px solid #0b6eff;
          background: #e7f4ff;
          color: #0b6eff;
        }
        &.valued {
          color: #0b6eff;
        }
        span {
          display: inline-block;
          max-width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .arrow {
          width: 26px;
          height: 26px;
        }
      }
    }
    .filter-item {
      display: flex;
      align-items: center;
      .title {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24px;
        color: #555555;
        margin-right: 16px;
      }
      .custom-input {
        width: 430px;
        height: 51px;
        background: #fafcfe;
        border-radius: 6px;
        border: 2px solid #e4edf8;
        margin-left: 16px;
      }
      :deep(.el-input__wrapper) {
        background: #fafcfe;
        box-shadow: none;
      }
      :deep(.el-input__inner) {
        height: 100%;
        background: #fafcfe;
        font-size: 24px;
      }
    }
  }
  .school-list {
    width: 100%;
    height: calc(100% - 130px);
    padding-bottom: 10px;
    margin-top: 38px;
    overflow-y: scroll;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-auto-rows: 144px;
    align-items: start;
    gap: 20px;
  }
}
</style>
<style>
.el-cascader-panel .el-cascader-node {
  height: 50px !important;
  line-height: 50px !important;
  padding: 0 20px !important;
}

.el-cascader-panel .el-cascader-node__label {
  line-height: 50px !important;
  font-size: 24px;
}
.el-cascader-menu__wrap.el-scrollbar__wrap {
  height: 300px;
}
.el-icon {
  width: 24px;
}
</style>
